﻿/*********************************************************
 * Copyright(c) 2012-2015
 * Author:wangzhonghai
 * description：
 *       1、
 * history：
 *       1、wangzhonghai - 2015/5/5 17:54:43 - Add 
 * *******************************************************/

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using AopAndIocDemo.Biz.Logging;
using Newtonsoft.Json;
using PostSharp.Aspects;

namespace AopAndIocDemo.Biz.Aspect
{
    [Serializable]
    public sealed class LogAspect : OnMethodBoundaryAspect
    {
        private readonly string _enterMessage;
        private readonly string _exitMessage;
        private readonly bool _onlyException;

        private static readonly string LogTemplate = System.Environment.NewLine + " 类名:{0}" + System.Environment.NewLine +
                                                     " 方法:{1}" + System.Environment.NewLine + " 参数:{2}" +
                                                     System.Environment.NewLine + " Referer:{3}" +
                                                     System.Environment.NewLine + " Message:{4}" +
                                                     System.Environment.NewLine + " ExcuteTime:{5}" +
                                                     System.Environment.NewLine;

        private static readonly LoggerService LoggerService = new LoggerService();

        public LogAspect(string enterMessage = "", string exitMessage = "", bool onlyException = true)
        {
            this._enterMessage = enterMessage;
            this._exitMessage = exitMessage;
            this._onlyException = onlyException;
        }

        public override void OnEntry(MethodExecutionArgs args)
        {
            //LoggerService.Info(string.Format("Entering [ {0} ] ...{1}.{2},{3},{4}", args.Method, args.Instance.GetType().Name, args.Method.Name, _enterMessage, args.Method.DeclaringType != null ? args.Method.DeclaringType.FullName : ""));
            string log = string.Format(LogTemplate,
                args.Method.DeclaringType != null ? args.Method.DeclaringType.FullName : "",
                args.Method.Name,
                JsonConvert.SerializeObject(args.Method.GetParameters()), //args.Instance.GetType().Name,
                "",
                _enterMessage,
                "1s"
                );

            LoggerService.Info(log);

            base.OnEntry(args);
        }

        public override void OnExit(MethodExecutionArgs args)
        {
            //LoggHelper.WriteLog(LogType.Info, string.Format("Leaving [ {0} ] ...{1}.{2},{3}", args.Method, controllerName, actionName, message));
            LoggerService.Info(string.Format("Leaving [ {0} ] ...{1}.{2},{3},{4}", args.Method, args.Method,
                args.Instance.GetType().Name, args.Method.Name, _exitMessage));

            base.OnExit(args);
        }
    }
}